package dd.lo.practice;

import dd.lo.util.ImageUtils;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.property.SimpleStringProperty;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextField;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.BorderPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import javafx.stage.FileChooser;
import javafx.stage.Stage;
import org.apache.commons.lang3.math.NumberUtils;
import org.opencv.core.*;
import org.opencv.imgcodecs.Imgcodecs;
import org.opencv.imgproc.Imgproc;

import javax.imageio.ImageIO;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class ConvexHullDisplay extends Application {

    public static void start(String[] args) {
        launch(args);
    }

    private static final int DEFAULT_WIDTH = 1200;
    private static final int DEFAULT_HEIGHT = 900;

    private Mat srcImg;

    private SimpleStringProperty threshold; //灰度图做二极化时使用的阈值，该阈值以上的变为白色

    private ImageView imageView;

    private void imageProcess() {
        Task<Void> task = new Task<Void>() {
            @Override
            protected Void call() {
                if (null == srcImg || srcImg.empty()) return null;
                Mat grayImg = Mat.zeros(srcImg.size(), CvType.CV_32SC1);
                Imgproc.cvtColor(srcImg, grayImg, Imgproc.COLOR_BGR2GRAY);
                int thresholdValue = NumberUtils.toInt(threshold.getValue(), 160);
                if (thresholdValue > 255) thresholdValue = 255;
                Imgproc.threshold(grayImg, grayImg, thresholdValue, 255, Imgproc.THRESH_BINARY);
                List<MatOfPoint> vContours = new ArrayList<>();
                Mat vHierarchy = new Mat();
                Imgproc.findContours(grayImg, vContours, vHierarchy, Imgproc.RETR_TREE, Imgproc.CHAIN_APPROX_SIMPLE, new Point(0, 0));
                //遍历每个轮廓，寻找凸包
                if (vContours.size() < 1) {
                    System.out.println("没有找到轮廓");
                    return null;
                }
                List<MatOfPoint> hullContours = new ArrayList<>(vContours.size());
                for (int i = 0; i < vContours.size(); ++i) {
                    MatOfPoint contour = vContours.get(i);
                    MatOfInt vHull = new MatOfInt();
                    Imgproc.convexHull(contour, vHull, false);
                    if (!vHull.empty()) {
                        int[] ids = vHull.toArray();
                        Point[] hullPoints = new Point[ids.length];
                        Point[] contourPoints = contour.toArray();
                        for (int j = 0; j < ids.length; ++j) {
                            hullPoints[j] = contourPoints[ids[j]];
                        }
                        MatOfPoint hullContour = new MatOfPoint(hullPoints);
                        hullContours.add(hullContour);
                    }
                }
                Mat viewImg = Mat.zeros(grayImg.size(), CvType.CV_8UC3);
                for (int i = 0; i < vContours.size(); ++i) {
                    Scalar color = new Scalar(Math.random() * 255, Math.random() * 255, Math.random() * 255);
                    Imgproc.drawContours(viewImg, vContours, i, color,1, Imgproc.LINE_8, vHierarchy, 0, new Point());
                    Imgproc.drawContours(viewImg, hullContours, i, color,1, Imgproc.LINE_8, vHierarchy, 0, new Point());
                }
                //此时就可以得到图片的byte信息，在ByteArrayOutputStream中，然后就可以通过byte信息将图片load到Mat中
                ImageUtils.fitImgSize(viewImg, viewImg, DEFAULT_WIDTH, DEFAULT_HEIGHT);
                MatOfByte buffer = new MatOfByte();
                Imgcodecs.imencode(".jpeg", viewImg, buffer);
                Platform.runLater(() -> {
                    imageView.setImage(new Image(new ByteArrayInputStream(buffer.toArray())));
                });
                return null;
            }
        };
        new Thread(task).start();
    }

    @Override
    public void start(Stage stage) throws Exception {
        Button imgChooserBtn = new Button("选择图片");
        imgChooserBtn.setOnMouseClicked(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("选择图片");
            fileChooser.setInitialDirectory(new File(System.getProperty("user.home") + "/Downloads")
            );
            fileChooser.getExtensionFilters().addAll(new FileChooser.ExtensionFilter("All Images", "*.*"));
            File imgFile = fileChooser.showOpenDialog(stage);
            if (null == imgFile) return;
            srcImg = Imgcodecs.imread(imgFile.getAbsolutePath(), Imgcodecs.IMREAD_UNCHANGED);
            if (srcImg.empty()) System.out.println("图片读取失败");
            imageProcess();
        });
        threshold = new SimpleStringProperty();
        TextField thresholdInput = new TextField();
        threshold.bind(thresholdInput.textProperty());
        //Draw button
        Button drawButton = new Button("绘制");
        drawButton.setOnMouseClicked(e -> imageProcess());
        //关闭按钮
        Button exitBtn = new Button("关闭");
        exitBtn.setOnMouseClicked(e -> Platform.exit());
        VBox rows = new VBox(0);
        rows.setPadding(new Insets(10, 10, 0, 10));
        HBox row0 = new HBox(10);
        row0.setPadding(new Insets(5, 0, 5, 0));
        row0.getChildren().addAll(imgChooserBtn, new Text("阈值："), thresholdInput, drawButton, exitBtn);
        rows.getChildren().addAll(row0);
        imageView = new ImageView();
        BorderPane root = new BorderPane();
        root.setCenter(imageView);
        root.setBottom(rows);
        Scene scene = new Scene(root, DEFAULT_WIDTH, DEFAULT_HEIGHT + 50);
        stage.setScene(scene);
        stage.setTitle("寻找图片轮廓的凸包演示");
        stage.setResizable(false);
        stage.show();
    }
}
